package com.iven.xie.fboot.file.controller;

import com.iven.xie.fboot.file.config.CustomPropsConstants;
import com.iven.xie.fboot.file.fegin.ISysAccessoryService;
import com.iven.xie.fboot.platform.entity.SysAccessory;
import com.iven.xie.fboot.tools.controller.BaseController;
import com.iven.xie.fboot.tools.exception.NormalException;
import com.iven.xie.fboot.tools.result.ResultModel;
import com.iven.xie.fboot.tools.result.ResultStatus;
import com.iven.xie.fboot.tools.util.Constants;
import com.iven.xie.fboot.tools.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Objects;

/**
 * @author iven.xie
 */
@Api(tags = "文件接口")
@RestController
@RequestMapping("accessory")
@CrossOrigin(origins = "*", maxAge = 3600)
@PropertySource("classpath:constants.properties")
public class FileController extends BaseController {

    @Resource
    private ISysAccessoryService sysAccessoryService;

    @Autowired
    private CustomPropsConstants customPropsConstants;

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("upload")
    public ResultModel<String> upload(@RequestParam("file") MultipartFile file, String userId, @RequestParam("category") String category) {

        String originalName = file.getOriginalFilename();
        long fileSize = file.getSize();
        String ext = originalName.substring(originalName.lastIndexOf(".") + 1, originalName.length());
        String tmpName = genTmpFileName();
        String path = File.separator + category + File.separator + tmpName + "." + ext;
        try {
            File targetFile = new File(customPropsConstants.getUploadBasePath() + path);
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);
            SysAccessory accessory = getAcc(userId, originalName, Integer.parseInt(String.valueOf(fileSize)), path, category);
            return sysAccessoryService.upload(accessory);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultModel.defaultError(null);
    }

    @ApiOperation(value = "获取文件-文件对象", notes = "获取文件-文件对象")
    @GetMapping("open-body")
    public ResultModel<SysAccessory> uploadUrl(@RequestParam("id") String id) {
        SysAccessory accessory = sysAccessoryService.getById(id).getData();
        if (Objects.isNull(accessory)) {
            throw new NormalException("文件(" + id + ")不存在");
        }
        String path = customPropsConstants.getImageViewBasePath() + accessory.getPath();
        accessory.setPath(path);
        return new ResultModel(ResultStatus.SUCCESS, accessory);
    }

    @ApiOperation(value = "获取文件-流文件", notes = "获取文件-流文件")
    @GetMapping("open-file")
    public void uploadFile(@RequestParam("id") String id, HttpServletResponse response) throws IOException {
        SysAccessory accessory = sysAccessoryService.getById(id).getData();
        if (Objects.isNull(accessory)) {
            throw new NormalException("文件(" + id + ")不存在");
        }
        String path = customPropsConstants.getImageViewBasePath() + accessory.getPath();

        URL url = new URL(path);
        URLConnection conn = url.openConnection();
        InputStream inputStream = conn.getInputStream();

        response.reset();
        response.setContentType(conn.getContentType());
        //纯下载方式 文件名应该编码成UTF-8
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(accessory.getOriginalName(), "UTF-8"));

        byte[] buffer = new byte[1024];
        int len;
        OutputStream outputStream = response.getOutputStream();
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
    }

    @ApiOperation(value = "获取文件-自动跳转", notes = "获取文件-自动跳转")
    @GetMapping("open")
    public void upload(@RequestParam("id") String id, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        SysAccessory accessory = sysAccessoryService.getById(id).getData();
        if (accessory == null) {
            return;
        }
        String path = customPropsConstants.getImageViewBasePath() + accessory.getPath();
        try {
            response.sendRedirect(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private SysAccessory getAcc(String userId, String originalName, Integer fileSize, String path, String category) {
        SysAccessory accessory = new SysAccessory();
        accessory.setCreateTime(new Date());
        accessory.setCreateUser(userId);
        accessory.setIsDel(Constants.NEGATIVE);
        accessory.setOriginalName(originalName);
        accessory.setFileSize(fileSize);
        accessory.setPath(path);
        accessory.setCategory(category);
        return accessory;
    }

    private String genTmpFileName() {
        return DateUtil.dateString(new Date(), "yyyyMMddHHmmssssss");
    }

}
